package com.zoe.app.aspect;

import com.zoe.app.anno.AutoIdempotent;
import com.zoe.app.config.TokenService;
import com.zoe.app.exception.IdempotentException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author Zoe.Zhang
 * @date 2021/10/27
 * @description
 */
@Aspect
@Component
public class AopIdempotent {
    @Autowired
    private TokenService tokenService;
    private static final Logger logger = LoggerFactory.getLogger(AopIdempotent.class);

    @Pointcut(value = "@annotation(com.zoe.app.anno.AutoIdempotent)")
    public void idempotent() {
    }

    @Before("idempotent()")
    public void doBefore(JoinPoint joinPoint) throws IdempotentException {
        //获取方法，此处可将signature强转为MethodSignature
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoIdempotent annotation = method.getAnnotation(AutoIdempotent.class);
        if (annotation.enable()) {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            logger.info("开启了幂等验证");
            tokenService.verifyToken(request);
        }
    }
}
